package com.fowo.api.common.validator;

import com.fowo.api.common.messages.MessageKeys;
import com.fowo.api.common.messages.MessageUtils;
import com.fowo.api.common.util.SheetUtils;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class EnumsStringValidator implements ConstraintValidator<EnumsString, String> {
    private EnumsString annotation;

    @Override
    public void initialize(EnumsString constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    // 自定义验证消息国际化处理
    private void trySetValidationMessage(ConstraintValidatorContext context) {
        if (StringUtils.hasText(annotation.message()) && annotation.value().length > 0) {
            String optionsList = Arrays.stream(annotation.value()).map(MessageUtils::format).collect(Collectors.joining(", "));
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                    MessageUtils.format(annotation.message(), optionsList)
            )
                    .addConstraintViolation();
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        String s = SheetUtils.trim(value);
        if (StringUtils.hasText(s)) {
            List<String> labels = Arrays.stream(annotation.value()).map(MessageUtils::format).collect(Collectors.toList());
            if (annotation.flags()) {
                if(!Arrays.stream(s.split(",，")).allMatch(is -> is != null && labels.contains(SheetUtils.trim(is)))) {
                    trySetValidationMessage(context);
                    return false;
                }
            } else {
                if(!labels.contains(s)) {
                    trySetValidationMessage(context);
                    return false;
                }
            }
        }
        return true;
    }
}
